package com.shensi.appCollect.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.DesensitizedUtil;
import com.shensi.appCollect.pojo.AppUserInfo;
import com.shensi.appCollect.dao.AppUserInfoMapper;
import com.shensi.appCollect.dao.PosMachineMapper;
import com.shensi.appCollect.dao.StationMapper;
import com.shensi.appCollect.enums.CardRecordType;
import com.shensi.appCollect.enums.PrintEnum;
import com.shensi.appCollect.pojo.*;
import com.shensi.appCollect.service.OrderPrintService;
import com.shensi.appCollect.utils.FeiEPrinterUtil;
import com.shensi.appCollect.utils.Methods;
import com.shensi.appCollect.utils.exception.CustomException;
import com.shensi.appCollect.utils.redis.RedisCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class OrderPrintServiceImpl implements OrderPrintService {

    @Resource
    private PosMachineMapper posMachineMapper;

    @Resource
    private AppUserInfoMapper appUserInfoMapper;

    @Resource
    private RedisCacheUtil redisCacheUtil;

    @Resource
    private StationMapper stationMapper;

    @Override
    @Async
    public void printUpateEletronicCard(CustomerCardUseRecord customerCardUseRecord) {
        log.info("订单信息customerCardUseRecord【{}】", customerCardUseRecord);
        StationDeviceManager stationDevice = getStationDevice(customerCardUseRecord.getStationId().toString());
        String audio = getAudio(stationDevice,customerCardUseRecord);
        String upateEletronicCardContent = getUpateEletronicCardContent(customerCardUseRecord, stationDevice);
        String finalContent = audio + upateEletronicCardContent;
        printOrder(stationDevice, finalContent);

    }

    private void printOrder(StationDeviceManager stationDeviceManage, String content){
        log.info("小票机信息【{}】", stationDeviceManage);
        String deviceFactory = stationDeviceManage.getDeviceFactory();
        PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
        if(stationDeviceManage.getIsPrint() == 0){
            return;
        }
        String printRes = "";

        switch (printEnum){
            case YILIANYUNK4:

                Integer random6K4 = (int) ((Math.random() * 9 + 1) * 100000);
                //初始化控制器类
                Methods mK4= Methods.getInstance();
                Object tokenK4 = redisCacheUtil.getCacheObject("STATION:DEVICE:" + stationDeviceManage.getClientId());
                log.info("token:{}",tokenK4);
                if(Objects.nonNull(tokenK4)){
                    String print = mK4.print(stationDeviceManage.getClientId(),stationDeviceManage.getDeviceNo(), content, random6K4.toString(), tokenK4.toString());
                    log.info("小票机返回值{}",print);
                    org.json.JSONObject json = new org.json.JSONObject(print);
                    if("0".equals(json.getString("error"))){
                        break;
                    }
                }

                //初始化终端信息
                mK4.init(stationDeviceManage.getClientId(), stationDeviceManage.getClientSecret());
                //获取token
                String refreshTokenK4 = mK4.getFreedomToken();
                log.info("新的token{}",refreshTokenK4);
                //存入redis
                redisCacheUtil.setCacheObject("STATION:DEVICE:" + stationDeviceManage.getClientId(),refreshTokenK4,30, TimeUnit.DAYS);


                String printK4 = mK4.print(stationDeviceManage.getDeviceNo(), content, random6K4.toString());
                log.info("小票机返回值2{}",printK4);

                break;

            case YILIANYUN:
                Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);
                //初始化控制器类
                Methods m= Methods.getInstance();
                Object token = redisCacheUtil.getCacheObject("STATION:DEVICE:" + stationDeviceManage.getClientId());
                log.info("token:{}",token);
                if(Objects.nonNull(token)){
                    String print = m.print(stationDeviceManage.getClientId(),stationDeviceManage.getDeviceNo(), content, random6.toString(), token.toString());
                    log.info("小票机返回值{}",print);
                    org.json.JSONObject json = new org.json.JSONObject(print);
                    if("0".equals(json.getString("error"))){
                        break;
                    }
                }

                //初始化终端信息
                m.init(stationDeviceManage.getClientId(), stationDeviceManage.getClientSecret());
                //获取token
                String refreshToken = m.getFreedomToken();
                log.info("新的token{}",refreshToken);
                //存入redis
                redisCacheUtil.setCacheObject("STATION:DEVICE:" + stationDeviceManage.getClientId(),refreshToken,30, TimeUnit.DAYS);


                String print = m.print(stationDeviceManage.getDeviceNo(), content, random6.toString());
                log.info("小票机返回值2{}",print);
                break;
            case FEIE:
                String result = FeiEPrinterUtil.printReceipt(stationDeviceManage.getDeviceNo(), content.toString());
                org.json.JSONObject resJson = new org.json.JSONObject(result);
                if("ok".equals(resJson.get("msg"))){
                    printRes = "补打小票成功";
                }else {
                    printRes = "补打小票失败";
                }

                break;
            default:
                log.info("没有配置小票机，打印失败");
                break;
        }
    }

    private String getUpateEletronicCardContent(CustomerCardUseRecord customerCardUseRecord, StationDeviceManager stationDevice){
        String deviceFactory = stationDevice.getDeviceFactory();
        PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
        log.info("小票机类型【{}】", printEnum);
        Station station = stationMapper.selectStationById(stationDevice.getStationId());
        String stationName = station.getStationName();
        StringBuilder stringBuilder = new StringBuilder();
//        stringBuilder.append("<MS>0,0</MS>");

        //语音
        HashMap<String, String> audioMap = new HashMap<>();
        audioMap.put("手机尾号", customerCardUseRecord.getMobilePhone().substring(7,11));
        audioMap.put("充值金额", customerCardUseRecord.getAmt().toString() + "元");
        audioMap.put("赠送金额", customerCardUseRecord.getPresentAmt().toString() + "元");



        switch (printEnum){
            case YILIANYUNK4:
                stringBuilder.append("<FS2><center>" + stationName + "</center></FS2><BR>");
                stringBuilder.append("<center>【充值】</center><BR>");
                break;
            case YILIANYUN:
                stringBuilder.append("<FS2><center>" + stationName + "</center></FS2><BR>");
                stringBuilder.append("<center>【充值】</center><BR>");
                break;
            case FEIE:
                stringBuilder.append("<BOLD><C><B>" + stationName + "</B></C></BOLD><BR>");
                stringBuilder.append("<C>【充值】</C><BR>");
                break;
        }



        AppUserInfo appUserInfo = new AppUserInfo();
        appUserInfo.setStationId(customerCardUseRecord.getEnterpriseId());
        appUserInfo.setMobilePhone (customerCardUseRecord.getMobilePhone());
        AppUserInfo appUserInfoRes = appUserInfoMapper.getAppUserInfo(appUserInfo);

        String userName = "";
        if(Objects.nonNull(appUserInfoRes)){
            userName = appUserInfoRes.getBlogNickName();
        }

        log.info("用户信息【{}】", appUserInfoRes);
        stringBuilder.append("会员名称：").append(userName).append("<BR>");
        stringBuilder.append("手机号：").append(DesensitizedUtil.mobilePhone(appUserInfoRes.getMobilePhone())).append("<BR>");
        stringBuilder.append("订单编号：").append(customerCardUseRecord.getOrderNo()).append("<BR>");
        stringBuilder.append("支付方式：").append(CardRecordType.getByKey(customerCardUseRecord.getPayType(),CardRecordType.MANUAL_ADD).getName()).append("<BR>");

        switch (printEnum){
            case YILIANYUNK4:
                stringBuilder.append("充值金额：<FS>").append(customerCardUseRecord.getAmt()).append("元</FS><BR>");
                stringBuilder.append("赠送金额：<FS>").append(customerCardUseRecord.getPresentAmt()).append("元").append("</FS><BR>");
                stringBuilder.append("获得积分：<FS>").append(customerCardUseRecord.getIntegral()).append("</FS><BR>");
                break;
            case YILIANYUN:
                stringBuilder.append("充值金额：<FS>").append(customerCardUseRecord.getAmt()).append("元</FS><BR>");
                stringBuilder.append("赠送金额：<FS>").append(customerCardUseRecord.getPresentAmt()).append("元").append("</FS><BR>");
                stringBuilder.append("获得积分：<FS>").append(customerCardUseRecord.getIntegral()).append("</FS><BR>");
                break;
            case FEIE:
                stringBuilder.append("<BOLD>充值金额：").append(customerCardUseRecord.getAmt()).append("元</BOLD><BR>");
                stringBuilder.append("<BOLD>赠送金额：").append(customerCardUseRecord.getPresentAmt()).append("元").append("</BOLD><BR>");
                stringBuilder.append("<BOLD>获得积分：").append(customerCardUseRecord.getIntegral()).append("</BOLD><BR>");
                break;
        }

        stringBuilder.append("充值时间：").append(DateUtil.format(customerCardUseRecord.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN)).append("<BR>");
        stringBuilder.append("-------------------------------<BR>");
        stringBuilder.append("打印时间：").append(DateUtil.now()).append("<BR>");

        stringBuilder.append("谢谢惠顾！欢迎下次再来~");
        stringBuilder.append("<BR>");
        stringBuilder.append("<BR>");
        stringBuilder.append("<BR>");


        if(!printEnum.equals(PrintEnum.FEIE)){
            return stringBuilder.toString().replace("<BR>", "\r\n");
        }
        return stringBuilder.toString();
    }

    private StationDeviceManager getStationDevice(String stationId){
        log.info("打印退款小票");
        StationDeviceManager stationDeviceManager=new StationDeviceManager();
        stationDeviceManager.setStationId(Integer.valueOf(stationId));
        stationDeviceManager.setDeviceType("3");
        List<StationDeviceManager>  stationDeviceManagers= posMachineMapper.getStationDeviceManagerList(stationDeviceManager);
        if(CollectionUtils.isEmpty(stationDeviceManagers)){
            throw new CustomException("当前油站没有配置小票机");
        }
        return stationDeviceManagers.get(0);
    }

    private String getAudio(StationDeviceManager stationDevice, CustomerCardUseRecord customerCardUseRecord){
        String deviceFactory = stationDevice.getDeviceFactory();
        PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);


        HashMap<String, String> audioMap = new HashMap<>();
        audioMap.put("手机尾号", customerCardUseRecord.getMobilePhone().substring(7,11));
        audioMap.put("充值金额", customerCardUseRecord.getAmt().toString() + "元");
        audioMap.put("赠送金额", customerCardUseRecord.getPresentAmt().toString() + "元");




        switch (printEnum){
            case YILIANYUNK4:
                StringBuffer sb = new StringBuffer();
                String rechargeAudio = stationDevice.getAudio();
                List<String> audioList = Arrays.asList(rechargeAudio.split(";"));
                String rechargeAudioString = audioList.get(2);
                log.info("充值订单语音播报rechargeAudio{}",rechargeAudioString);
                List<String> rechargeAudioList = Arrays.asList(rechargeAudioString.split(","));
                StringBuffer sbK4 = new StringBuffer();
                for (String s : rechargeAudioList) {
                    if("充值金额".equals(s)){
                        sbK4.append("<VN>6</VN>").append("<VD>").append(customerCardUseRecord.getAmt()).append("</VD>").append("<VN>0</VN>");
                    }
                    if("手机尾号".equals(s)){
                        if(StringUtils.isNotBlank(customerCardUseRecord.getMobilePhone()) && Validator.isMobile(customerCardUseRecord.getMobilePhone())){
                            String mobilePhoneK4 = customerCardUseRecord.getMobilePhone().substring(7,11);
                            log.info("mobilePhone{}",mobilePhoneK4);
                            char[] charsK4 = mobilePhoneK4.toCharArray();
                            log.info("charsK4{}",charsK4);
                            sbK4.append("<VN>").append(1).append("</VN>");
                            for (char aChar : charsK4) {
                                sbK4.append("<VD>").append(aChar).append("</VD>");
                            }
                        }
                    }
                    if("赠送金额".equals(s)){
                        BigDecimal presentAmt = customerCardUseRecord.getPresentAmt();
                        sbK4.append("<VN>7</VN>").append("<VD>").append(Objects.nonNull(presentAmt) ? presentAmt : "0").append("</VD>").append("<VN>0</VN>");
                    }
                }
                log.info("k4语音【{}】", sbK4);
                return sbK4.toString();
            case YILIANYUN:
                StringBuffer sb1 = new StringBuffer();
                try {

                    String rechargeAudio1 = stationDevice.getAudio();
                    List<String> audioList1 = Arrays.asList(rechargeAudio1.split(";"));
                    String rechargeAudioString1 = audioList1.get(2);
                    log.info("充值订单语音播报rechargeAudio{}",rechargeAudioString1);
                    List<String> rechargeAudioList1 = Arrays.asList(rechargeAudioString1.split(","));
                    sb1.append("<audio>");
                    for (String audioContent : rechargeAudioList1) {
                        sb1.append(audioContent + audioMap.get(audioContent));
                    }
                    sb1.append("</audio>");
                }catch (Exception e){
                    sb1 = new StringBuffer("<audio>手机尾号").append(customerCardUseRecord.getMobilePhone().substring(7,11))
                            .append("充值金额").append(customerCardUseRecord.getAmt()).append("元").append("赠送金额").append(customerCardUseRecord.getPresentAmt()).append("元</audio>");

                }
                log.info("易联云语音【{}】", sb1);
                return sb1.toString();

            case FEIE:

              return "";
        }
                return "";
    }
}
